class Solution {
public:
    int getDepth(TreeNode *root) {
        if (!root) return 0;
        else return max(getDepth(root->left), getDepth(root->right)) + 1;
    }

    bool isBalanced(TreeNode* root) {
        if (!root) return true;
        return abs(getDepth(root->left) - getDepth(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
    }
};

class Solution2 {
public:
    int getDepth(TreeNode *root) {
        if (!root) return 0;
        int leftDepth = getDepth(root->left);
        int rightDepth = getDepth(root->right);
        if (leftDepth == -1 || rightDepth == -1 || abs(leftDepth - rightDepth) > 1)
            return -1;
        else
            return max(leftDepth, rightDepth) + 1;
    }

    bool isBalanced(TreeNode* root) {
        return getDepth(root) >= 0;
    }
};